<template>
	<view class="goods-list">
		<view v-for="item in goodsList" :key="item.goodsid">
			<shop-good :goodsimg="item.goodsimg" :goodsname="item.goodsname" :goodsprice="item.goodsbaseprice" :merchantsname="item.merchantsname" @click.native="gotoGoodsDetail(item)"></shop-good>
		</view>
	</view>
</template>

<script>
	export default {
		onLoad(state) {
			// 将从其他页面跳转过来的参数转存到data中
			state.cateid && (this.cateid = state.cateid)
			state.query && (this.query = state.query)
			state.cateid && this.getGoodsByCateid()
			state.query && this.getGoodsByQuery()
		},
		onReachBottom() {
			!this.isFinish && this.page++
			if(this.cateid.trim() !== '') {
				this.getGoodsByCateid()
			} else if(this.query.trim() !== '') {
				this.getGoodsByQuery()
			}
		},
		data() {
			return {
				// 存储从其他页面发送过来的查询信息
				query: '',
				// 存储从其他页面发送过来的数据
				cateid: '',
				// 存储该商品分类下的商品信息
				goodsList: [],
				page: 1,
				num: 10,
				isReachingBottomRequest: false,
				isFinish: false
			}
		},
		methods: {
			// 根据商品分类信息获取指定分类下所有的商品
			async getGoodsByCateid() {
				if(this.isReachingBottomRequest || this.isFinish) return
				this.isReachingBottomRequest = true
				const { data: res } = await uni.$http.get('/goods', { cateid: this.cateid, page: this.page, num: this.num  })
				if(res.meta.status !== 200) return uni.showToast({
					title: '失败',
					icon: 'error',
					duration: 1000
				})
				this.goodsList = [...this.goodsList, ...res.recordset]
				if(res.recordset.length === 0) this.isFinish = true
				this.isReachingBottomRequest = false
			},
			// 根据商品名模糊查询
			async getGoodsByQuery() {
				if(this.isReachingBottomRequest || this.isFinish) return
				this.isReachingBottomRequest = true
				const { data: res } = await uni.$http.get('/goods', { querytext: this.query, page: this.page, num: this.num })
				if(res.meta.status !== 200) return uni.showToast({
					title: '失败',
					icon: 'error',
					duration: 1000
				})
				this.goodsList = [...this.goodsList, ...res.recordset]
				if(res.recordset.length === 0) this.isFinish = true
				this.isReachingBottomRequest = false
			},
			// 商品大致信息框被点击时跳转至商品详情页
			gotoGoodsDetail(item) {
				uni.navigateTo({
					url: `../goodsdetail/goodsdetail?id=${ item.goodsid }&mid=${ item.merchantsid }`
				})
			}
		}
	}
</script>

<style>

</style>
